package com.igs.parse.quartz;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;

import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.loyin.model.DownloadUrl;

public class DowLoadHtml
{
	private static Logger log = Logger.getLogger(DowLoadHtml.class);

	public static DownloadUrl downLoadHtml(DownloadUrl du) throws Exception
	{
		try
		{
			String imgTag = "pic";
			String baseURI = du.getUrl();
			URI baseUri = new URI(baseURI);// 基本网页URI
			// 从 URL 直接加载 HTML 文档
			Document doc = Jsoup.connect(baseURI).timeout(20000).get();
			// 下载图片，并且将图片路径改成绝对路径
			Elements imgs = doc.getElementsByTag("img");
			int iii = 1;
			for (Element img : imgs)
			{
				try
				{
					String relativePath = img.attr("src");
					System.out.println("当前正在下载网站：" + du.getTitle() + du.getUrl());
					System.out.println("当前正在下载图片：" + relativePath);
					if (relativePath == null && relativePath.trim().equals(""))
						continue;
					URI abs = baseUri.resolve(relativePath);// 解析于上述网页的相对URL，得到绝对URI
					URL absURL = abs.toURL();// 转成URL
					String imgPath = absURL.toString();
					int beginIndex = imgPath.lastIndexOf(".");
					int endIndex = imgPath.length();
					if (imgPath.indexOf("?") >= 0)
						endIndex = imgPath.indexOf("?");
					String hzm = imgPath.substring(beginIndex, endIndex);
					try
					{
						URLConnection uc = absURL.openConnection();
						uc.setReadTimeout(20000);
						InputStream is = uc.getInputStream();
						String dlPath = FinalStringUtil.downLoadBackupPath + du.getId() + "\\";
						File dlFolder = new File(dlPath);
						dlFolder.mkdirs();
						dlPath = dlPath + imgTag + iii + hzm;
						File file = new File(dlPath);
						FileOutputStream out = new FileOutputStream(file);
						int i = 0;
						while ((i = is.read()) != -1)
						{
							out.write(i);
						}
						is.close();
						img.attr("src", imgTag + iii + hzm);
					} catch (Exception ex)
					{
						log.error("下载一张图片异常", ex);
					}
					System.out.println(img.toString());
					iii++;
				} catch (Exception ex)
				{
					log.error("下载所有图片异常", ex);
				}
			}
			// //将所有的src，href改成绝对路径
			updateUrlPath(doc, "link", baseUri);
			updateUrlPath(doc, "script", baseUri);
			updateUrlPath(doc, "a", baseUri);
			// 输出下载页面的html代码
			String htmlFilePath = FinalStringUtil.downLoadBackupPath + du.getId() + "\\" + du.getId() + ".htm";
			writeHtmlFile(htmlFilePath, doc.html());
			// //获取文件夹的大小
			long folderSize = getFolderSize(FinalStringUtil.downLoadBackupPath + du.getId() + "\\");
			long folderKb = folderSize / 1024;
			du.setDownloadsize(folderKb);
			du.setIsdownload(1);
			return du;
		} catch (Exception ex1)
		{
			log.error("下载网页异常", ex1);
			du.setIsdownload(-1);
			return du;
		}
	}

	public static void writeHtmlFile(String htmlFilePath, String htmlContentStr)
	{
		try
		{
			OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(htmlFilePath), "UTF-8");
			out.write(htmlContentStr);
			out.flush();
			out.close();

		} catch (Exception ex)
		{
			log.error("写网页异常", ex);
		}
	}

	public static void updateUrlPath(Document doc, String tagName, URI baseUri) throws Exception
	{
		try
		{
			Elements imgs = doc.getElementsByTag(tagName);
			for (Element img : imgs)
			{
				String href = img.attr("href");
				if (href != null && href.trim().equals("") == false && href.toUpperCase().startsWith("HTTP") == false)
				{
					href = href.trim();
					URI abs = baseUri.resolve(href);// 解析于上述网页的相对URL，得到绝对URI
					URL absURL = abs.toURL();// 转成URL
					String imgPath = absURL.toString();
					img.attr("href", imgPath);
				}
				String src = img.attr("src");
				if (src != null && src.trim().equals("") == false && src.toUpperCase().startsWith("HTTP") == false)
				{
					src = src.trim();
					URI abs = baseUri.resolve(src);// 解析于上述网页的相对URL，得到绝对URI
					URL absURL = abs.toURL();// 转成URL
					String imgPath = absURL.toString();
					img.attr("src", imgPath);
				}
			}
		} catch (Exception ex)
		{
			log.error("更新url地址异常", ex);
		}
	}

	public static long getFolderSize(String fileFolderPath)
	{
		long folderSize = 0;
		File folder = new File(fileFolderPath);
		File[] files = folder.listFiles();
		for (File f : files)
		{
			folderSize = folderSize + f.length();
		}
		return folderSize;
	}

	public static void deleteFolder(String fileFolderPath)
	{
		File folder = new File(fileFolderPath);
		if(folder.exists()==false)
			return ;
		File[] files = folder.listFiles();
		for (File f : files)
		{
			f.delete();
		}
		folder.delete();
		return;
	}
	
	public static void deleteDownLoadHtml(long id)
	{
		String htmlFolderPath = FinalStringUtil.downLoadBackupPath + id;
		deleteFolder(htmlFolderPath);
		String htmlZipPath = FinalStringUtil.downLoadBackupPath +  id + ".zip";
		File zipFile=new File(htmlZipPath);
		if(zipFile.exists())
			zipFile.delete();
	}
	
	public static boolean isDownload(long id)
	{
		String htmlFilePath = FinalStringUtil.downLoadBackupPath + id + "\\" + id + ".htm";
		File htmlFile = new File(htmlFilePath);
		if(htmlFile.exists())
			return true;
		return false;
	}
	
	public static String zipHtmlFile(long id)
	{
		String htmlZipPath = FinalStringUtil.downLoadBackupPath +  id + ".zip";
		File htmlZipFile = new File(htmlZipPath);
		if(htmlZipFile.exists()==false)
		{
			ZipCompress zca = new ZipCompress(htmlZipPath);
			String zipFolder=FinalStringUtil.downLoadBackupPath +  id ;
	        zca.compress(zipFolder);   
		}
		return htmlZipPath;
	}
}
